<template>
	<view class="zaiui-publish-page">
		<!--标题栏-->
		<bar-title bgColor='bg-white'>
			<block slot="content">发布闲置</block>
			<block slot="right">
				<text class="text-gray" @tap="showPreview">预览</text>
			</block>
		</bar-title>

		<scroll-view class="zaiui-scroll-view" scroll-y>
			<!--分类信息-->
			<view class="zaiui-section bg-white">
				<view class="zaiui-section-title">选择分类</view>
				<view class="zaiui-category-info" @tap="selectCategory" :class="{ 'has-category': category }">
					<template v-if="category">
						<view class="cu-avatar round lg" :style="{ backgroundImage: 'url(' + category.icon + ')' }" />
						<view class="category-text">
							<view class="text-black text-lg">{{ category.name || category.title }}</view>
							<view class="text-gray text-sm">{{ category.desc || category.text || '已选择分类' }}</view>
						</view>
					</template>
					<template v-else>
						<view class="cu-avatar round lg bg-gray">
							<text class="cuIcon-add text-white" />
						</view>
						<view class="category-text">
							<view class="text-black text-lg">选择商品分类</view>
							<view class="text-gray text-sm">点击选择商品所属分类</view>
						</view>
					</template>
					<text class="cuIcon-right text-gray" />
				</view>
			</view>

			<!--商品信息-->
			<view class="zaiui-section bg-white">
				<view class="zaiui-section-title">商品信息</view>

				<!--商品描述-->
				<view class="zaiui-form-item">
					<view class="zaiui-label">商品描述</view>
					<view class="zaiui-input-box">
						<textarea class="zaiui-textarea-large" v-model="formData.description"
							placeholder="请输入商品描述，AI将自动为您优化..." maxlength="500"
							@input="autoShowAiTip" />
						<view class="zaiui-input-footer">
							<view class="text-count">{{ formData.description.length }}/500</view>
							<view class="zaiui-ai-tip-corner" v-if="formData.description || showAiTipAlways"
								@tap="aiPolishDescription">
								<text class="cuIcon-magic text-blue" />
								<text class="text-sm text-blue">AI润色</text>
							</view>
						</view>
					</view>
				</view>

				<!--商品图片-->
				<view class="zaiui-form-item">
					<view class="zaiui-label">商品图片</view>
					<view class="zaiui-upload-box">
						<view class="zaiui-upload-item" v-for="(img, index) in formData.images" :key="index">
							<image class="upload-image" :src="img" mode="aspectFill" />
							<text class="cuIcon-close delete-btn" @tap="deleteImage(index)" />
						</view>
						<view class="zaiui-upload-btn" @tap="chooseImage" v-if="formData.images.length < 9">
							<text class="cuIcon-add text-gray" />
							<text class="text-sm text-gray">添加图片</text>
						</view>
					</view>
					<view class="zaiui-tip text-gray">最多可上传9张图片</view>
				</view>

				<!--商品价格-->
				<view class="zaiui-form-item">
					<view class="zaiui-label">商品价格</view>
					<view class="zaiui-price-box">
						<text class="price-symbol">¥</text>
						<input class="zaiui-price-input" type="number" v-model="formData.price" placeholder="现价"
							@blur="validatePrice" />
					</view>
				</view>

				<!--原价-->
				<view class="zaiui-form-item">
					<view class="zaiui-label">原价</view>
					<view class="zaiui-price-box">
						<text class="price-symbol">¥</text>
						<input class="zaiui-price-input" type="number" v-model="formData.originalPrice"
							placeholder="原价（可选）" />
					</view>
					<view class="zaiui-tip text-gray" v-if="category">
						该分类商品均价参考：¥{{ getCategoryAvgPrice() }}
					</view>
				</view>
			</view>
		</scroll-view>

		<!--底部操作栏-->
		<view class="zaiui-footer-bar">
			<view class="zaiui-footer-content">
				<button class="cu-btn bg-gray round" @tap="cancelPublish">取消</button>
				<button class="cu-btn bg-red round" @tap="nextStep" :disabled="!canSubmit">
					下一步
				</button>
			</view>
		</view>

		<!--分类选择弹窗-->
		<view class="zaiui-category-modal" :class="showCategoryModal ? 'show' : ''">
			<category :show="showCategoryModal" @closeTap="categorySelect" />
		</view>

		<!--AI润色弹窗-->
		<view class="cu-modal" :class="showAiModal ? 'show' : ''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">AI润色建议</view>
					<view class="action" @tap="hideAiModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-sm">
					<view class="ai-suggestion-box">
						<view class="ai-suggestion-item" v-for="(suggestion, index) in aiSuggestions" :key="index"
							@tap="useSuggestion(suggestion)">
							<text class="cuIcon-check text-green" v-if="selectedSuggestion === index" />
							<text class="cuIcon-round text-gray" v-else />
							<text class="suggestion-text">{{ suggestion }}</text>
						</view>
					</view>
					<view class="margin-top">
						<button class="cu-btn bg-red round" @tap="applyAiSuggestion">使用选中建议</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import barTitle from '@/components/basics/bar-title';
import category from '@/components/view/category';
import storage from '@/utils/storage';
import aiApi from '@/api/ai';
import uploadApi from '@/api/upload';

export default {
	components: {
		barTitle,
		category
	},
	data() {
		return {
			category: null, // 选择的分类信息
			formData: {
				description: '',
				images: [],
				price: '',
				originalPrice: '',
				categoryId: '0'
			},
			categoryList: [],
			showCategoryModal: false, // 分类选择弹窗
			showAiModal: false, // AI润色弹窗
			aiSuggestions: [], // AI建议列表
			selectedSuggestion: -1, // 选中的建议
			showAiTipAlways: true, // 始终显示AI润色提示
			categoryPrices: {
				'phone': 1500,
				'book': 50,
				'digital': 800,
				'clothing': 120,
				'vehicle': 2000,
				'children': 180,
				'electronics': 600,
				'furniture': 350,
				'outdoor': 280,
				'beauty': 85,
				'computer': 2500,
				'jewelry': 450,
				'food': 35,
				'pet': 120,
				'instrument': 1200,
				'collectible': 800
			}
		}
	},
	computed: {
		// 是否可以提交
		canSubmit() {
			return this.formData.description && this.formData.images.length > 0 && this.formData.price > 0;
		}
	},
	async onLoad() {
		
	},
	methods: {
		// 选择图片并上传
		async chooseImage() {
			uni.showLoading({
				title: '选择图片中...'
			});

			try {
				const res = await new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 9 - this.formData.images.length,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera'],
						success: resolve,
						fail: reject
					});
				});

				// 显示上传进度
				uni.showLoading({
					title: '上传图片中...'
				});
				// 直接使用uni.chooseImage返回的tempFilePaths进行上传
				const uploadResult = await uploadApi.uploadMultiple(res.tempFilePaths);

				if (uploadResult.success && uploadResult.data) {
					// 处理上传结果，提取图片URL（后端返回数组格式）
					const uploadedUrls = uploadResult.data.map(item => item.url);
					
					// 将上传成功的图片URL添加到图片列表
					this.formData.images = [...this.formData.images, ...uploadedUrls];
					
					uni.showToast({
						title: `成功上传${uploadedUrls.length}张图片`,
						icon: 'success'
					});
				} else {
					throw new Error(uploadResult.message || '图片上传失败');
				}
			} catch (error) {
				console.error('图片上传失败:', error);
				uni.showToast({
					title: '图片上传失败，请重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 删除图片
		async deleteImage(index) {
			const imageUrl = this.formData.images[index];
			
			// 如果是已上传的图片（包含服务器URL），则调用API删除
			if (imageUrl && imageUrl.includes('http')) {
				try {
					// 从URL中提取文件名
					const filename = imageUrl.split('/').pop();
					if (filename) {
						await uploadApi.deleteImage(filename);
					}
				} catch (error) {
					console.error('删除服务器图片失败:', error);
					// 即使删除失败，也继续从本地列表中移除
				}
			}
			
			// 从本地图片列表中移除
			this.formData.images.splice(index, 1);
			
			uni.showToast({
				title: '图片已删除',
				icon: 'success'
			});
		},

		// 选择分类
		selectCategory() {
			this.showCategoryModal = true;
		},

		// 取消分类选择
		categorySelect() {
			this.showCategoryModal = false;
			this.category = this.$store.getters['category/getCurrentCategory'];
			if (this.category) {
				this.formData.categoryId = this.category.id;
			}
		},

		// 自动显示AI提示
		autoShowAiTip() {
			// 当用户开始输入时，确保AI润色提示可见
			if (this.formData.description && this.formData.description.length > 0) {
				this.showAiTipAlways = true;
			}
		},


		// AI润色描述
		aiPolishDescription() {
			if (!this.formData.description) {
				uni.showToast({
					title: '请先输入商品描述',
					icon: 'none'
				});
				return;
			}
			this.generateAiSuggestions();
		},

		// 生成AI建议 - 调用后端AI服务
		async generateAiSuggestions() {
			uni.showLoading({
				title: 'AI思考中...'
			});

			try {
				// 调用AI API生成商品描述
				const goodsData = {
					title: this.formData.description, // 商品标题/描述
					category: this.category ? this.category.title : '商品',
					condition: '二手',
					price: this.formData.price
				};
				
				const result = await aiApi.generateGoodsDescription(goodsData);

				if (result && result.description) {
					this.aiSuggestions = this.createDescriptionVariants(result.description);
					this.selectedSuggestion = 0;
					this.showAiModal = true;
				} else {
					throw new Error('AI服务响应异常');
				}
			} catch (error) {
				console.error('AI润色失败:', error);
				// 如果AI服务不可用，使用本地备用方案
				this.aiSuggestions = this.createFallbackSuggestions();
				this.selectedSuggestion = 0;
				this.showAiModal = true;
				
				uni.showToast({
					title: 'AI服务暂时不可用，已使用备用方案',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 创建描述变体
		createDescriptionVariants(baseDescription) {
			const category = this.category ? this.category.title : '商品';
			const price = this.formData.price;
			
			return [
				baseDescription,
				`${baseDescription} - ${category}优质二手，性价比高，现价仅${price}元`,
				`【二手${category}】${baseDescription}，功能完好，实物拍摄，价格实惠`,
				`个人闲置${baseDescription}，${category}成色新，可小刀，欢迎咨询`
			];
		},

		// 创建备用建议方案
		createFallbackSuggestions() {
			const baseDesc = this.formData.description;
			const category = this.category ? this.category.title : '商品';
			const price = this.formData.price;

			return [
				`${baseDesc} - ${category}优质二手，性价比高，现价仅${price}元`,
				`【二手${category}】${baseDesc}，功能完好，实物拍摄，价格实惠`,
				`个人闲置${baseDesc}，${category}成色新，可小刀，欢迎咨询`,
				`精品${baseDesc}，${category}自用转让，价格${price}元，包邮到家`
			];
		},

		// AI价格建议
		async aiSuggestPrice() {
			if (!this.formData.description || this.formData.description.trim() === '') {
				uni.showToast({
					title: '请先填写商品描述',
					icon: 'none'
				});
				return;
			}

			this.priceLoading = true;
			
			try {
				// 调用AI API获取价格建议
				const priceData = {
					title: this.formData.description, // 商品标题/描述
					category: this.category ? this.category.title : '商品',
					condition: '二手'
				};
				
				const result = await aiApi.suggestPrice(priceData);

				if (result.success) {
					const priceResponse = result.data;
					
					// 显示价格建议弹窗
					this.priceSuggestion = {
						suggestedPrice: priceResponse.suggestedPrice || 0,
						priceRange: priceResponse.priceRange || { min: 0, max: 0 },
						explanation: priceResponse.explanation || '基于市场行情和商品状况给出的建议价格'
					};
					
					this.showPriceModal = true;
				} else {
					throw new Error('AI价格建议服务响应异常');
				}
			} catch (error) {
				console.error('AI价格建议失败:', error);
				uni.showToast({
					title: '价格建议服务暂时不可用',
					icon: 'none'
				});
			} finally {
				this.priceLoading = false;
			}
		},

		// 隐藏AI弹窗
		hideAiModal() {
			this.showAiModal = false;
		},

		// 选择建议
		useSuggestion(suggestion) {
			const index = this.aiSuggestions.indexOf(suggestion);
			this.selectedSuggestion = index;
		},

		// 应用AI建议
		applyAiSuggestion() {
			if (this.selectedSuggestion >= 0) {
				this.formData.description = this.aiSuggestions[this.selectedSuggestion];
				this.hideAiModal();
				uni.showToast({
					title: '描述已更新',
					icon: 'success'
				});
			}
		},

		// 验证价格
		validatePrice() {
			if (this.formData.price < 0) {
				this.formData.price = '';
				uni.showToast({
					title: '价格不能为负数',
					icon: 'none'
				});
			}
		},

		// 获取分类均价
		getCategoryAvgPrice() {
			if (!this.category) return '0';
			return this.categoryPrices[this.category.type] || '0';
		},

		// 预览
		showPreview() {
			if (!this.canSubmit) {
				uni.showToast({
					title: '请完善商品信息',
					icon: 'none'
				});
				return;
			}

			uni.showModal({
				title: '商品预览',
				content: `描述：${this.formData.description}\n现价：¥${this.formData.price}\n原价：${this.formData.originalPrice ? '¥' + this.formData.originalPrice : '未填写'}\n图片：${this.formData.images.length}张`,
				showCancel: false
			});
		},

		// 取消发布
		cancelPublish() {
			uni.navigateBack();
		},

		// 下一步
		nextStep() {
			if (!this.canSubmit) {
				uni.showToast({
					title: '请完善商品信息',
					icon: 'none'
				});
				return;
			}
			storage.set('publishData', this.formData);
			// 跳转到规格填写页面
			uni.navigateTo({
				url: '/pages/goods/specs'
			});
		},



		// 根据分类智能生成规格
		generateSpecsByCategory() {
			if (!this.category) return {};

			const categoryTitle = this.category.title;
			const specs = {};

			// 根据分类智能生成规格
			switch (categoryTitle) {
				case '手机':
					specs.brand = '请选择品牌';
					specs.model = '请填写型号';
					specs.condition = '请选择成色';
					specs.storage = '请选择内存';
					break;
				case '图书影音':
					specs.type = '请选择类型';
					specs.author = '请填写作者/出版社';
					specs.condition = '请选择新旧程度';
					break;
				case '数码':
					specs.brand = '请选择品牌';
					specs.model = '请填写型号';
					specs.condition = '请选择成色';
					break;
				case '服装鞋帽':
					specs.brand = '请选择品牌';
					specs.size = '请选择尺码';
					specs.condition = '请选择新旧程度';
					break;
				default:
					specs.condition = '请选择商品状态';
					specs.detail = '请填写商品描述';
			}

			return specs;
		}
	}
}
</script>

<style lang="scss" scoped>
.zaiui-publish-page {
	min-height: 100vh;
	background: #FAFAFA;

	.zaiui-scroll-view {
		height: calc(100vh - 100rpx - 100rpx - env(safe-area-inset-bottom)); /* 减去标题栏和底部操作栏高度 */
	}

	.zaiui-section {
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 30rpx;

		.zaiui-section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 30rpx;
			border-left: 6rpx solid #e54d42;
			padding-left: 20rpx;
		}

		.zaiui-category-info {
			display: flex;
			align-items: center;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 12rpx;

			.category-text {
				margin-left: 20rpx;
				flex: 1;
			}
		}
	}

	.zaiui-form-item {
		margin-bottom: 40rpx;
		position: relative;

		.zaiui-label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
			font-weight: 500;
		}

		.zaiui-input-box {
			position: relative;

			.zaiui-textarea {
				width: 100%;
				height: 120rpx;
				background: #f8f8f8;
				border-radius: 12rpx;
				padding: 20rpx;
				font-size: 28rpx;
				line-height: 1.5;
			}

			.zaiui-textarea-large {
				width: 100%;
				height: 280rpx;
				background: #f8f8f8;
				border-radius: 16rpx;
				padding: 30rpx;
				font-size: 32rpx;
				line-height: 1.6;
				border: 2rpx solid #e8e8e8;
				transition: all 0.3s ease;
			}

			.zaiui-textarea-large:focus {
				border-color: #e54d42;
				background: #fff;
				box-shadow: 0 0 0 4rpx rgba(229, 77, 66, 0.1);
			}

			.zaiui-input-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 10rpx;

				.text-count {
					font-size: 24rpx;
					color: #999;
				}

				.zaiui-ai-tip-corner {
					display: flex;
					align-items: center;
					gap: 8rpx;
					padding: 8rpx 16rpx;
					background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
					border-radius: 20rpx;
					border: 1rpx solid #1890ff;

					.cuIcon-magic {
						font-size: 28rpx;
						color: #1890ff;
						animation: pulse 2s infinite;
					}

					.text-sm {
						font-size: 24rpx;
						font-weight: 500;
						color: #1890ff;
					}
				}
			}
		}



		.zaiui-upload-box {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.zaiui-upload-item {
				position: relative;
				width: 160rpx;
				height: 160rpx;
				border-radius: 12rpx;
				overflow: hidden;

				.upload-image {
					width: 100%;
					height: 100%;
				}

				.delete-btn {
					position: absolute;
					top: 0;
					right: 0;
					background: rgba(0, 0, 0, 0.5);
					color: white;
					padding: 8rpx;
					border-radius: 0 0 0 12rpx;
				}
			}

			.zaiui-upload-btn {
				width: 160rpx;
				height: 160rpx;
				border: 2rpx dashed #ddd;
				border-radius: 12rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.cuIcon-add {
					font-size: 48rpx;
					margin-bottom: 10rpx;
				}
			}
		}

		.zaiui-price-box {
			display: flex;
			align-items: center;
			background: #f8f8f8;
			border-radius: 12rpx;
			padding: 0 20rpx;
			height: 80rpx;

			.price-symbol {
				font-size: 32rpx;
				color: #e54d42;
				font-weight: bold;
			}

			.zaiui-price-input {
				flex: 1;
				height: 100%;
				font-size: 32rpx;
				padding: 0 20rpx;
			}

			.zaiui-ai-price-suggestion {
				display: flex;
				align-items: center;
				gap: 8rpx;
				padding: 8rpx 16rpx;
				background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
				border-radius: 20rpx;
				border: 1rpx solid #1890ff;
				margin-left: 20rpx;
				cursor: pointer;
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.95);
					background: linear-gradient(135deg, #e6f3ff 0%, #d9edff 100%);
				}

				.cuIcon-magic {
					font-size: 28rpx;
					color: #1890ff;
					animation: pulse 2s infinite;
				}

				.text-sm {
					font-size: 24rpx;
					font-weight: 500;
					color: #1890ff;
				}
			}
		}

		.zaiui-tip {
			margin-top: 10rpx;
			font-size: 24rpx;
		}
	}

	.zaiui-footer-bar {
		position: fixed;
		bottom: 0rpx;
		left: 0;
		right: 0;
		background: white;
		padding: 20rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-top: 1rpx solid #eee;

		.zaiui-footer-content {
			display: flex;
			justify-content: space-between;
			gap: 20rpx;

			.cu-btn {
				flex: 1;
				height: 80rpx;
				font-size: 32rpx;

				&:disabled {
					background: #ccc !important;
					color: #999 !important;
				}
			}
		}
	}

	.ai-suggestion-box {
		max-height: 400rpx;
		overflow-y: auto;
		border: 1rpx solid #e8ecff;

		.ai-suggestion-item {
			display: flex;
			align-items: flex-start;
			border-radius: 12rpx;
			margin-bottom: 16rpx;
			padding: 24rpx;
			background: white;
			border: 1rpx solid #e8ecff;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
			transition: all 0.3s ease;
			cursor: pointer;

			&:last-child {
				margin-bottom: 0;
			}

			&:hover {
				transform: translateY(-2rpx);
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
				border-color: #1890ff;
			}

			&.active {
				background: linear-gradient(135deg, #e6f7ff 0%, #f0fdff 100%);
				border-color: #1890ff;
				box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.15);
			}

			.cuIcon-check,
			.cuIcon-round {
				margin-right: 20rpx;
				font-size: 36rpx;
				margin-top: 4rpx;
				flex-shrink: 0;

				&.cuIcon-check {
					color: #52c41a;
					animation: checkPulse 2s infinite;
				}

				&.cuIcon-round {
					color: #d9d9d9;
				}
			}

			.suggestion-text {
				flex: 1;
				font-size: 28rpx;
				line-height: 1.6;
				text-align: left;
				color: #262626;
				font-weight: 400;

				&::before {
					content: "💡 ";
					color: #1890ff;
					font-weight: bold;
				}
			}
		}
	}

	@keyframes pulse {
		0% {
			opacity: 1;
			transform: scale(1);
		}

		50% {
			opacity: 0.7;
			transform: scale(1.1);
		}

		100% {
			opacity: 1;
			transform: scale(1);
		}
	}

	@keyframes checkPulse {
		0% {
			opacity: 1;
			transform: scale(1);
		}

		50% {
			opacity: 0.8;
			transform: scale(1.2);
			box-shadow: 0 0 0 8rpx rgba(82, 196, 26, 0.3);
		}

		100% {
			opacity: 1;
			transform: scale(1);
			box-shadow: none;
		}
	}

	@keyframes fadeInUp {
		0% {
			opacity: 0;
			transform: translateY(20rpx);
		}

		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/* 分类选择弹窗样式 */
	.zaiui-category-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		overflow-y: auto;
		background: rgba(0, 0, 0, 0.5);
		display: none;
		z-index: 99999;
		
		&.show {
			display: block;
		}
	}
}
</style>